package com.nowcoder.community.event;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.constant.CommunityConstant;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.AliOssUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 事件消费者
 * @author 花木凋零成兰
 * @date 2024/3/24 17:33
 */
@Component
@Slf4j(topic = "EventConsumer.class")
public class EventConsumer {

    @Resource
    private MessageService messageService;

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private ElasticsearchService elasticsearchService;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Resource
    private AliOssUtil aliOssUtil;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    /**
     * 处理多个主题消息
     * @param record 消息封装
     */
    @KafkaListener(topics = {CommunityConstant.TOPIC_COMMENT, CommunityConstant.TOPIC_LIKE, CommunityConstant.TOPIC_FOLLOW})
    public void handleTopicMessage(ConsumerRecord<String, String> record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空!");
            return ;
        }
        // 将消息字符串转化为 事件对象
        Event event = JSONObject.parseObject(record.value(), Event.class);
        if (event == null) {
            log.error("消息格式有误!");
            return ;
        }
        // 发送站内通知
        // 构造通知
        Message message = Message.builder()
                .fromId(CommunityConstant.SYSTEM_USER_ID)
                .toId(event.getEntityUserId())
                .conversationId(event.getTopic())
                .createTime(new Date())
                .build();
        // 通知内容
        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        if (!event.getData().isEmpty()) {
            content.putAll(event.getData());
        }
        message.setContent(JSONObject.toJSONString(content));
        // 存入持久层
        messageService.addMessage(message);

    }

    /**
     * 消费 发布帖子 有关事件
     */
    @KafkaListener(topics = {CommunityConstant.TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord<String, String> record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空!");
            return ;
        }
        // 将消息字符串转化为 事件对象
        Event event = JSONObject.parseObject(record.value(), Event.class);
        if (event == null) {
            log.error("消息格式有误!");
            return ;
        }

        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());  // 根据事件中实体id 查询帖子数据
        elasticsearchService.saveDiscussPost(discussPost);  // 保存帖子同步到 Elasticsearch

    }

    /**
     * 消费 删除帖子 有关事件
     * @param record
     */
    @KafkaListener(topics = {CommunityConstant.TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord<String, String> record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空!");
            return ;
        }
        // 将消息字符串转化为 事件对象
        Event event = JSONObject.parseObject(record.value(), Event.class);
        if (event == null) {
            log.error("消息格式有误!");
            return ;
        }
        elasticsearchService.deleteDiscussPost(event.getEntityId());  // 删除帖子同步到 Elasticsearch
    }

    @KafkaListener(topics = CommunityConstant.TOPIC_SHARE)
    public void handleShareMessage(ConsumerRecord<String, String> record) {
        if (record == null || record.value() == null) {
            log.error("消息内容为空!");
            return ;
        }
        // 将消息字符串转化为 事件对象
        Event event = JSONObject.parseObject(record.value(), Event.class);
        if (event == null) {
            log.error("消息格式有误!");
            return ;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");

        String cmd = wkImageCommand + " --quality 75 "
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            Runtime.getRuntime().exec(cmd);     // 执行 生成图片语句
            log.warn("生成长图成功：" + cmd);      // 比生成图片语句更早执行
        } catch (IOException e) {
            log.error("生成长图失败：{}", e.getMessage());
        }

        // 使用定时器 监视生成图片命令完成 图片生成完 则上传至 阿里云
        UploadTask task = new UploadTask(fileName, suffix);
        Future future =  taskScheduler.scheduleAtFixedRate(task, 500);   // 每隔500毫秒执行一遍
        task.setFuture(future);

    }

    class UploadTask implements Runnable {

        // 文件名称
        private String fileName;
        // 文件后缀
        private String suffix;

        // 启动任务的返回值 用于停止定时器
        @Setter
        private Future future;

        // 任务开始时间
        private long startTime;

        // 上传次数
        private int uploadCounts;

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        @Override
        public void run() {
            // 生成失败
            if (System.currentTimeMillis() - startTime > 30000) {
                log.error("执行时间过长，终止任务：{}", fileName);
                future.cancel(true);
                return ;
            }
            // 上传失败
            if (uploadCounts >= 3) {
                log.error("上传次数过多，终止任务：{}", fileName);
                future.cancel(true);
                return ;
            }

            // 本地存放文件目录：
            String path = wkImageStorage + "/" + fileName + suffix;
            File file = new File(path);
            if (file.exists()) {
                log.error("开始第{}次上传{}", ++ uploadCounts, fileName);
                // 开始上传图片到云服务器
                try {
                    FileInputStream fis = new FileInputStream(file);    // 读取文件流
                    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();  // 文件读取成字节
                    byte[] buffer = new byte[1024]; // 缓冲区
                    int len = -1;
                    while ((len = fis.read(buffer)) != -1) {
                        byteArray.write(buffer, 0, len);
                    }
                    byteArray.flush();
                    String uploadName = aliOssUtil.upload(byteArray.toByteArray(), fileName + suffix);

                    if (uploadName == null || StringUtils.isBlank(uploadName)) {
                        log.error("第{}次文件上传失败[{}]", uploadCounts, fileName);
                    } else {
                        log.warn("第{}次文件上传成功[{}]", uploadCounts, fileName);
                        future.cancel(true); // 任务结束
                    }

                } catch (IOException e) {
                    log.info("第{}次上传文件失败[{}]", uploadCounts, fileName);
                }
            } else {
                log.info("等待图片生成：[{}]", fileName);
            }


        }
    }

}
